# Setup environment ----
library(parallel)
library(data.table)
library(bigKRLS)
source("R/functions.R")
results_path <- "results/replication/"
RNGkind("L'Ecuyer-CMRG")
qs <- c(list("actual", "zero"), as.list(seq(.95, .05, -.01)))
set.seed(1961685937)
house_seeds <- sample.int(.Machine$integer.max, length(qs))
senate_seeds <- sample.int(.Machine$integer.max, length(qs))

#     House KRLS counterfactuals ----
load(paste0(results_path, "house_analysis_data.RData"))
load.bigKRLS(paste0(results_path, "house_krls_model"),
  newname = "house_krls_model")
house_krls_counterfactuals <- mclapply(seq_along(qs), function(i) {
  type_or_quantile <- qs[[i]]
  set.seed(house_seeds[[i]])
  cat("\n", format(Sys.time()), type_or_quantile)
  make_counterfactuals(type_or_quantile, house_krls_model, house_data)
}, mc.cores = 6)
save(house_krls_counterfactuals,
  file = paste0(results_path, "house_krls_counterfactuals.RData"))

# Senate KRLS counterfactuals ----
load(paste0(results_path, "senate_analysis_data.RData"))
load.bigKRLS(paste0(results_path, "senate_krls_model"),
  newname = "senate_krls_model")
senate_krls_counterfactuals <- mclapply(seq_along(qs), function(i) {
  set.seed(senate_seeds[[i]])
  cat("\n", format(Sys.time()), qs[[i]])
  make_counterfactuals(qs[[i]], senate_krls_model, senate_data)
}, mc.cores = 6)
save(senate_krls_counterfactuals,
  file = paste0(results_path, "senate_krls_counterfactuals.RData"))